package com.cennavi.list;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.cennavi.dbs.MongoPool;
import com.mongodb.DBCollection;

public class DataVersionList extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4178274509719295091L;

	/**
	 * Constructor of the object.
	 */
	public DataVersionList() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods",
				"POST, GET, OPTIONS, DELETE,PUT");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();

		try {

			String table = "datalist";

			DBCollection collection = MongoPool.getDB().getCollection(table);
			
			List<String> kj_versions = collection.distinct("coord");
			
			List<String> time_version = collection.distinct("version");
			
			List<String> names = collection.distinct("data_type");
			
			JSONObject json = new JSONObject();
			
			JSONArray ja_jk = new JSONArray();
			
			for(String s:kj_versions)
				ja_jk.add(s);
			
			json.put("kj_version", ja_jk);
			
			JSONArray ja_time = new JSONArray();
			
			for(String s:time_version)
				ja_time.add(s);
			
			json.put("time_version", ja_time);
			
			JSONArray ja_name = new JSONArray();
			
			for(String s:names)
				ja_name.add(s);
			
			json.put("names", ja_name);
			
			out.println(json.toString());

		} catch (Exception e) {
			out.println("{\"error_code\":-1,\"error_msg\":\"" + e.getMessage()
					+ "\"}");
		} finally {
			out.flush();

			out.close();
		}

	}

	public void init() throws ServletException {
		// Put your code here
	}

}
